from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.models.AdminRole import AdminRole
from app.models.AdminUser import AdminUser
import datetime
from app.models.AdminActionLog import AdminActionLog
from masonite.facades import Session
from app.my_package.MyPackage import MyValidator


class AdminBindRoleController(Controller):
    uri = '/admin/bind-role'
    temp = 'admin.bind-role'

    def create(self, request: Request, response: Response, view: View):
        admin_user_id = request.input('admin_user_id')
        b, m = MyValidator.is_integer(admin_user_id)
        if b is False:
            return response.json({'code': 0, 'message': '未知管理员'})

        admin_user = AdminUser.where('id', admin_user_id).first()
        if admin_user is None:
            return response.json({'code': 0, 'message': "未知管理员"})

        data = {
            'uri': self.uri,
            'admin_user_id': admin_user_id,
            'admin_role_id': admin_user.admin_role_id,
            'roles': AdminRole.get_title(),
            'account': admin_user.account,
        }
        return view.render(self.temp + '.create', data)

    def store(self, request: Request, response: Response):
        admin_user_id = request.input('admin_user_id')
        admin_role_id = request.input('admin_role_id')

        b, m = MyValidator.is_integer(int(admin_user_id))
        b2, m2 = MyValidator.is_integer(int(admin_role_id))
        if b is False or b2 is False:
            return response.json({'code': 0, 'message': '参数错误'})

        admin_user = AdminUser.where('id', admin_user_id).first()
        if admin_user is None:
            return response.json({'code': 0, 'message': '未知管理员'})

        admin_role = AdminRole.where('id', admin_role_id).first()
        if admin_role is None:
            return response.json({'code': 0, 'message': "未知角色"})
        if admin_user.admin_role_id != int(admin_role_id):
            updated_at = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            admin_user.update({'admin_role_id': admin_role_id, 'updated_at': updated_at})
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":绑定{0}".format(admin_role.title)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})
